package com.tgy.myplus.基础学习.Thread.Synchronized;

/**
 * @author 送你一块二向箔
 * @date 2021/11/08 15:23
 */

/*
会出现-1，0，不安全
 */
public class UnsafeTickets {
    public static void main(String[] args) {
        ByuTickets byuTickets = new ByuTickets();
        Thread thread = new Thread(byuTickets,"甲");
        Thread thread1 = new Thread(byuTickets,"乙");
        Thread thread2 = new Thread(byuTickets,"丙");
        thread.start();
        thread1.start();
        thread2.start();
    }

}


class ByuTickets implements Runnable{
    private int tickets = 10;
    private boolean flag = true;


    @Override
    public void run() {
        while (flag) {
            try {
                Thread.sleep(20);
                buy();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    private synchronized void buy(){
        if (tickets <= 0) {
            flag = false;
            return;
        }
        System.out.println(Thread.currentThread().getName()+"买到了第"+tickets--);
    }
}
